﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;
using System.IO;

namespace h2100
{
    /// <summary>
    /// Quản lý bản đồ (và các công trình nằm trên bản đồ)
    /// </summary>
    public class hMapManager : hEntityManager
    {
        private hMap _terrainMap;
        private hStructureManager _structureManager;
        private hParams args;

        #region Properties

        public hMap Map
        {
            get { return _terrainMap; }
            set { _terrainMap = value; }
        }

        public hStructureManager StructureManager
        {
            get { return _structureManager; }
            set { _structureManager = value; }
        }

        #endregion

        Dictionary<String, String> tileDict;
        string[] arrType;
        int ntilename;

        /// <summary>
        /// Đọc tập tin cấu hình cho địa hình
        /// </summary>
        /// <param name="content"></param>
        /// <param name="_args"></param>
        /// <param name="fileName">Tên file cấu hình địa hình ("Terrain.hcf")</param>
        public hMapManager(ContentManager content, hParams _args, String fileName)
        {
            args = _args;
    
            StreamReader reader = new StreamReader(fileName);

            String tmp;

            ntilename = int.Parse(reader.ReadLine());
            arrType = new string[ntilename];
            tileDict = new Dictionary<string, string>();
            for (int i = 0; i < ntilename; i++)
            {
                string idx = reader.ReadLine().Split('#')[0];             
                tmp = reader.ReadLine();
                tileDict.Add(idx, tmp.Split('=')[1]);
                tmp = reader.ReadLine();
                arrType[i] = tmp.Split('=')[1];
            }

            reader.Close();
        }

        ///// <summary>
        ///// Phân tích kiểu ô bản đồ
        ///// </summary>
        ///// <param name="str"></param>
        ///// <returns></returns>
        //public hGlobal.MapCellType typeParse(string str)
        //{
        //    switch (str.Trim())
        //    {
        //        case "Unusable":
        //            return hGlobal.MapCellType.Unusable;
        //        case "BuildingPlatform":
        //            return hGlobal.MapCellType.BuildingPlatform;
        //        case "EnemyBuildingPlatform":
        //            return hGlobal.MapCellType.EnemyBuildingPlatform;
        //        case "NormalTerrain":
        //            return hGlobal.MapCellType.NormalTerrain;
        //        case "AbnormalTerrain":
        //            return hGlobal.MapCellType.AbnormalTerrain;
        //        case "EnergyField":
        //            return hGlobal.MapCellType.EnergyField;
        //        case "RawResourceField":
        //            return hGlobal.MapCellType.RawResourceField;
        //        default:
        //            return hGlobal.MapCellType.Unusable;
        //    }
        //}        
        
        /// <summary>
        /// Tạo bản đồ
        /// </summary>
        /// <param name="content"></param>
        /// <param name="fileName">Tên file bản đồ, lấy trong "Map.hcf"</param>
        /// <param name="_args"></param>
        public void createMap(ContentManager content, hParams _args, String fileName )
        {
            StreamReader reader = new StreamReader(fileName);

            String tmp;

            tmp = reader.ReadLine();

            int mapRows = int.Parse(tmp.Split(' ')[0]);
            int mapColumns = int.Parse(tmp.Split(' ')[1]);

            args.Grid = new hGrid(mapRows, mapColumns);

            String[] argsTerrain = new String[mapColumns * mapRows];
            string[] argType = new string[mapColumns * mapRows];
            for (int i = 0; i < mapRows; i++)
            {
                tmp = reader.ReadLine();
                for (int j = 0; j < mapColumns; j++)
                {
                    argsTerrain[i * mapColumns + j] = tileDict[tmp.Split(' ')[j]];
                    argType[i * mapColumns + j] = arrType[int.Parse(tmp.Split(' ')[j])];
                }
            }

            tmp = reader.ReadLine();

            String[] argsStructure = new String[mapColumns * mapRows];
            for (int i = 0; i < mapRows; i++)
            {
                tmp = reader.ReadLine();
                for (int j = 0; j < mapColumns; j++)
                {
                    argsStructure[i * mapColumns + j] = tmp.Split(' ')[j];
                }
            }

            _terrainMap = new hMap(content, mapRows, mapColumns, argsTerrain, argType);

            // Đưa công trình vào quản lý
            _structureManager = new hStructureManager(content, args);

            for (int i = 0; i < mapRows; i++)
            {
                for (int j = 0; j < mapColumns; j++)
                {
                    if (!argsStructure[i * mapColumns + j].Equals("0"))
                    {
                        _structureManager.createObject(int.Parse(argsStructure[i * mapColumns + j]), i, j);
                    }
                }
            }

            reader.Close();
        }

        public void clearFog(Vector2 point)
        {
            _terrainMap.clearFog(point);
        }

        public int nDelay = 1;
        protected int iDelay = 0;

        public void update(hParams args, GameTime gameTime)
        {
            args.HightlightingMapCell = null;
            args.Grid.update(args);
            _terrainMap.update(args, gameTime);
            _structureManager.update(args, gameTime); 

            MouseState mouse = Mouse.GetState();

            
            // không xử lý chuột nếu chuột trên control panel
            if (!args.IsMouseOverControlPanel)
            {              
                if (mouse.LeftButton == ButtonState.Pressed)
                {                    
                    if (args.ControlPhase == hGlobal.ControlPhase.Selecting)
                    {
                        if (args.SelectedMapCell != null)
                        {
                            args.SelectedMapCellPosition = new Vector2(args.SelectedMapCell.X, args.SelectedMapCell.Y);
                        }
                    }
                }
            }                    
        }

        public void draw(GameTime gtime, SpriteBatch sb)
        {
            _terrainMap.draw(gtime, sb);
            _structureManager.draw(gtime, sb);
        }

        public int getEnergy()
        {
            return _structureManager.getEnergy();
        }
    } 
}
